<template>
  <!-- 创建对话框 -->
  <ga-modal v-model:visible="visible" :title="isEdit ? '编辑系统' : '创建系统'" @close="closeCreateDialog" width="735px">
    <ga-form :model="form" ref="formRef" :rules="rules">
      <BorderBox class="m_b_16">
        <template v-slot:title_l>勾选资源新建业务</template>
        <template v-slot:main_info>
          <ga-form-item field="name" label="系统名称" label-col-flex="80px" required>
            <ga-input v-model="form.name" />
          </ga-form-item>
          <ga-form-item field="scorePolicyId" label="评分规则" label-col-flex="80px" required>
            <ga-select v-model="form.scorePolicyId" :style="{ width: '100%' }">
              <ga-option v-for="item in scoreRules " :key="item.id" :value="item.id" :label="item.name">
              </ga-option>
            </ga-select>
          </ga-form-item>
          <ga-form-item field="resourceWorkloads" label="选择资源" label-col-flex="80px">
            <ga-tree-select v-model="selected" :allow-search="true" :allow-clear="true" :tree-checkable="true"
              :data="treeData" placeholder="Please select ..." style="width:100%" :load-more="loadMore"
              :tree-checked-strategy="treeCheckedStrategy" @change="handlechange" />
          </ga-form-item>
        </template>
      </BorderBox>
      <!-- <BorderBox class="m_b_16">
      <template v-slot:title_l>设置匹配规则</template>
      <template v-slot:main_info>
        <ga-form-item v-for="(item, index) in matchingRules" :key="index" :label="index===0?'匹配规则':''" label-col-flex="80px">   
          <ga-input placeholder="请输入内容" v-model="item.value"/>
          <ga-button type="text" @click="handleDelete(index)" :style="{marginLeft:'10px'}">删除</ga-button>
        </ga-form-item>
        <ga-button type="text" @click="handleAdd" style="border-color:rgb(44 64 104 / 16%);width:74px;margin-left:22px;">+新增</ga-button>
      </template>
    </BorderBox> -->
    </ga-form>
    <template #footer>
      <ga-button type="primary" @click="handleSubmit">确定</ga-button>
      <ga-button @click="closeCreateDialog">取消</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, defineExpose, toRefs } from 'vue'
import { fetchSystemDetail, fetchScoreRules, fetchResourceTree, checkSystem, createSystem, updateSystem } from '@/api/system.js'
import { Modal, Message } from '@garco-design/web-vue'

const props = defineProps({
  isEdit: {
    required: false,
    default: true
  },
  record: {
    required: false,
    default: null
  }
})

const { isEdit, record } = toRefs(props)
const emits = defineEmits([
  "fetchData",
])
const handlechange = (val) => {
  console.log('val--', val)
}
const visible = ref(false)
const form = ref({
  name: "",
  scorePolicyId: "",
  resourceWorkloads: {
    mergeLabel: "",
    nameBak: null,
    masterIp: "",
    clusterName: "",
    namespace: "",
    workloadKind: "",
    workloadName: "",
    isEntrance: null,
    systemServiceId: null,
    merge: null,
    isSrc: null,
    srcWorkload: false
  }
})
const formRef = ref()
const selected = ref([]);
const treeCheckedStrategy = ref('child');
const scoreRules = ref([]);
const treeData = ref([]);
const resourceArray = ref([])
const rules = {
  name: [
    {
      required: true,
      message: '请输入系统名称',
    },
    {
      validator: async (value, cb) => {
        if (!value.trim()) {
          // If the value is empty or only contains spaces
          cb(new Error('系统名称不能为空'));
        } else {
          const { data } = await checkSystem(value);
          if (data) {
            cb(new Error('该系统名称已存在'))
          } else {
            cb()
          }
        }
      },
      trigger: ['blur', 'input'],
    },
  ],
}
const resourceKey = ref([])
const open = async () => {
  visible.value = true;
  getScoreRules()
  getResouce()
  if (isEdit.value) {
    console.log('record', record.value);
    form.value.name = record.value.name
    const { data } = await fetchSystemDetail(record.value.id)
    console.log("data.resourceWorkloads", data.resourceWorkloads);
    form.value.scorePolicyId = data.scorePolicyId
    // selected.value = ["busybox"]
    selected.value = reverseTransformSelect(data.resourceWorkloads)
    console.log("selected", selected.value);
  }
}

const getScoreRules = () => {
  fetchScoreRules().then((res) => {
    if (res && res.code === 20000) {
      const { data } = res
      scoreRules.value = data
    }
  })
}

const getResouce = () => {
  fetchResourceTree().then((res) => {
    if (res && res.code === 20000) {
      const { data } = res
      // console.log("data", data);
      resourceArray.value = Object.entries(data)
      // console.log("resourceArray.value", resourceArray.value);
      // 转换数据
      treeData.value = resourceArray.value.map(([cluster, namespaces]) => ({
        key: cluster,
        title: cluster,
      }));
      resourceKey.value = transformResource(resourceArray.value)
      // console.log(treeData.value);
    }
  })
}

const transformData = (data) => {
  return Object.entries(data).map(([namespace, workloads]) => ({
    key: namespace,
    title: namespace,
    children: workloads.map(workload => ({
      // key: Object.entries(workload),
      key: Object.entries(workload),
      title: workload.workloadName,
    }))
  }));
}



const loadMore = (nodeData) => {
  const { title, key } = nodeData;
  // console.log("nodeData",nodeData);
  const matchedItem = resourceArray.value.find(
    ([clusterTitle, namespaces]) => clusterTitle === title
  );
  const children = matchedItem ? transformData(matchedItem[1]) : [];
  return new Promise((resolve) => {
    setTimeout(() => {
      nodeData.children = children;
      resolve();
    }, 1000);
  });
};

const closeCreateDialog = () => {
  visible.value = false
  formRef.value.resetFields()
  selected.value = []
}

const handleSubmit = async () => {
  const res = await formRef.value.validate()
  if (!res) {
    try {
      console.log("selected", selected.value);
      form.value.resourceWorkloads = transformSelect(selected.value)
      console.log("transformed", transformSelect(selected.value));
      // console.log("form", form.value);
      if (isEdit.value) {
        const { code } = await updateSystem(record.value.id, form.value)
        if (code === 20000) {
          Message.success('更新系统成功')
        }
      } else {
        const { code } = await createSystem(form.value)
        if (code === 20000) {
          Message.success('创建系统成功')
        }
      }
    } catch (error) {
      Message.error('操作失败')
    }
    visible.value = false
    emits("fetchData")
  }

}

function transformResource(data) {
  const transformDataArray = [];
  for (const [key, value] of data) {
    for (const [subKey, subValueArray] of Object.entries(value)) {
      subValueArray.forEach(item => {
        const workloadName = item.workloadName;
        transformDataArray.push({ [workloadName]: item });
      });
    }
  }
  return transformDataArray;
}

function transformSelect(data) {
  return data.map(item => {
    // 使用reduce函数将内部的键值对数组转换为一个对象  
    //reduce函数的累加器（acc）初始化为一个空对象{}，然后通过每次迭代将新的键值对添加到这个对象中。
    return item.reduce((acc, [key, value]) => {
      acc[key] = value;
      return acc;
    }, {});
  });
}

function reverseTransformSelect(data) {
  // 假设 data 是 transformSelect 函数输出的结构  
  // 即 data 是一个数组，每个元素都是一个对象  
  return data.map(itemObj => {
    // 我们需要将对象转换回键值对的内部数组格式  
    // 这里使用 Object.entries 来获取对象的键值对数组  
    return Object.entries(itemObj);
  });
}

defineExpose({ open })

</script>
<style lang="scss" scoped></style>